/*
 *  Copyright 2019-2025 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.server.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import me.zhengjie.dao.MergeTaskDao;
import me.zhengjie.dao.MesSyncDao;
import me.zhengjie.mapper.MesSyncMapper;
import me.zhengjie.server.MesSyncService;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.SnowIdUtil;
import me.zhengjie.vo.mes.ResponseResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;


/**
 * @author laoxu
 * @description 服务实现
 * @date 2025-06-26
 **/
@Service
@RequiredArgsConstructor
public class MesSyncServiceImpl extends ServiceImpl<MesSyncMapper, MesSyncDao> implements MesSyncService {

    private final MesSyncMapper mesSyncMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(MesSyncDao resources) {
        mesSyncMapper.insert(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(MesSyncDao resources) {
        MesSyncDao mesSyncDao = getById(resources.getId());
        mesSyncDao.copy(resources);
        mesSyncMapper.updateById(mesSyncDao);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<String> ids) {
        mesSyncMapper.deleteBatchIds(ids);
    }

    @Override
    public void download(List<MesSyncDao> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (MesSyncDao mesSyncDao : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("物料的编号", mesSyncDao.getMaterialCode());
            map.put("物料的名称", mesSyncDao.getMaterialName());
            map.put("物料分类", mesSyncDao.getMaterialType());
            map.put("物料分类名称（原料、辅料、半成品）", mesSyncDao.getMaterialTypeName());
            map.put("物料的有效期（天数）", mesSyncDao.getDormancyPeriod());
            map.put("物料规格", mesSyncDao.getMaterialSpecs());
            map.put("物料单位", mesSyncDao.getMaterialUnit());
            map.put("supplierCustomer", mesSyncDao.getSupplierCustomer());
            map.put("记录更新时间", mesSyncDao.getUpdateTime());
            map.put("超发限额", mesSyncDao.getOverissueLimit());
            map.put("标准重量", mesSyncDao.getStandardWeight());
            map.put("有效期", mesSyncDao.getExpiryPeriod());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public MesSyncDao findMesSyncByMaterialCode(String materialCode) {
        LambdaQueryWrapper<MesSyncDao> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MesSyncDao::getMaterialCode, materialCode);
        return this.getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<?> materialSyncMES(ResponseResult<List<MesSyncDao>> result) {
        List<MesSyncDao> obj = result.getReturnData();
        if (obj == null) {
            return ResponseResult.error("同步物料数据参数为空！");
        }

        try {
            List<MesSyncDao> mesSyncUpdateList = new ArrayList<>();
            List<MesSyncDao> mesSyncInsertList = new ArrayList<>();
            for (MesSyncDao mesSyncDao : obj) {
                MesSyncDao daoByCode = findMesSyncDaoByCode(mesSyncDao.getMaterialCode());
                if (daoByCode == null) {
                    daoByCode = new MesSyncDao().setId(String.valueOf(SnowIdUtil.nextId()));
                    daoByCode.copy(mesSyncDao);
                    mesSyncInsertList.add(daoByCode);
                    continue;
                }
                daoByCode.copy(mesSyncDao);
                mesSyncUpdateList.add(daoByCode);
            }
            this.saveBatch(mesSyncInsertList);
            this.saveBatch(mesSyncUpdateList);
        } catch (Exception e) {
            return ResponseResult.error("同步更新物料数据失败！");
        }
        return ResponseResult.success("同步更新物料数据成功！");
    }

    public MesSyncDao findMesSyncDaoByCode(String materialCode) {
        LambdaQueryWrapper<MesSyncDao> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MesSyncDao::getMaterialCode, materialCode);
        return this.getOne(wrapper);
    }


}